﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SqlCon;

namespace yfxt
{
    public partial class gl_dbckd_zuo : Form
    {
        public gl_dbckd_zuo()
        {
            InitializeComponent();
        }

        string comStr;
        int tabSB = 0;    //在申领数量的列，防止按了Tab直接跳到下一行，而没有进行CellValueChanged的（计算金额和合计）
        int totalparameter = 0;    //dataGridView1.Rows[i].Cells[1].Value为null会报错，所以添加一个变量来避免报错((申领数量回车)当第一行数据显示在datagridView1上，值变为1)
        int tan_tishi;   //按确认按钮不弹提示框，变量 1为不弹，0为弹
        string ypmc;
        public string shenqingdanhao2;

        /// <summary>
        /// 退出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void gl_dbckd_zuo_Load(object sender, EventArgs e)
        {
            dataGridView1.AllowUserToResizeRows = false;                     //禁止用鼠标调整datagridView单元格的大小。
            dataGridView1.AllowUserToResizeColumns = false;
            foreach (DataGridViewColumn c in dataGridView1.Columns)        //禁止对datagridView列进行排序
            {
                c.SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            shenqingdanhao2 = ((gl_dbck)this.Owner).shenqingdanhao2;
            DataTable dt = new DataTable();
            DataTable dt2 = new DataTable();

            //显示No.100001
            label6.Text = shenqingdanhao2;

            //显示入库日期、备注、领药员、申请药房
            comStr = "select t.bzxx,t1.ygxm,t3.yfmc from YF_DB01 t,GY_YGDM t1,yf_yflb t3 where t.sqdh='" + shenqingdanhao2 + "' "+
                "and t.czgh=t1.ygbh and t.sqyf=t3.yfsb";
            dt2.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
            textBox2.Text = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd").Replace('-', '.');
            textBox3.Text = dt2.Rows[0][0].ToString();
            textBox4.Text = dt2.Rows[0][1].ToString();
            textBox1.Text = dt2.Rows[0][2].ToString();

            //显示合计
            comStr = "select sum(lsje) from YF_DB02 where sqdh='" + shenqingdanhao2 + "'";
            string total_lsje = (SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null)).ToString();
            textBox6.Text = total_lsje;

            //显示datagridView1的
            comStr = "select t1.ypmc,t.yfgg,t.yfdw,t2.cdqc,t.lsjg,t.ypsl,t.qrsl,t.lsje,t3.ypsl from YF_DB02 t,yk_typk t1,YK_CDDZ t2,yf_kcmx t3,"+
                "YF_DB01 t4 where t.sqdh='" + shenqingdanhao2 + "' and t.ypxh=t1.ypxh and t2.ypcd=t.ypcd and t4.sqdh=t.sqdh "+
                "and t1.ypxh=t3.ypxh and t3.yfsb=t4.mbyf";
            dt.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dataGridView1.Rows.Add(1);

                for (int j = 0; j < 9; j++)
                {
                    if (dt.Rows[i][j].ToString() != "")
                    {
                        dataGridView1.Rows[i].Cells[j].Value = dt.Rows[i][j].ToString();
                    }
                }
            }

            dataGridView1.Columns[0].ReadOnly = true;
            dataGridView1.Columns[1].ReadOnly = true;
            dataGridView1.Columns[2].ReadOnly = true;
            dataGridView1.Columns[3].ReadOnly = true;
            dataGridView1.Columns[4].ReadOnly = true;
            dataGridView1.Columns[5].ReadOnly = true;
            dataGridView1.Columns[7].ReadOnly = true;
            dataGridView1.Columns[8].ReadOnly = true;
            this.Show();                          //Focus() 成功的关键代码
            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[6];
            this.dataGridView1.BeginEdit(true);
        }

        /// <summary>
        /// 确认按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            int feng=0;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.Rows[i].Cells[6].Value==null)
                {
                    MessageBox.Show("实发数量没有填写完整，请填写！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    feng =1;
                    return;
                }
            }
            if (feng==1)
	        {
                return;
	        }
            if (MessageBox.Show("是否确认调拨申请单" + "" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "" + "？",
                    "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    //更新调拨01、02表
                    decimal qrsl_var = Convert.ToDecimal(dataGridView1.Rows[i].Cells[6].Value);
                    string ypmc = dataGridView1.Rows[i].Cells[0].Value.ToString();
                    comStr = "update t set t.QRSL='" + qrsl_var + "' from YF_DB02 t,yk_typk t2 where t.sqdh='" + shenqingdanhao2 + "' and t2.ypmc='" + ypmc + "' " +
                        "and t.ypxh=t3.ypxh;" +
                        "update YF_DB01 set ckbz=1,ckgh='" + Program.ygbh + "',ckrq='" + DateTime.Now.ToString() + "' where sqdh='" + shenqingdanhao2 + "';";
                    SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);

                    //根据实发数量，更新库存    @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
                    DataTable dt0 = new DataTable();
                    comStr = "select ypsl,ypxh,ypph from yf_kcmx t,yk_typk t2 where t.ypxh=t2.ypxh and t2.ypmc='" + ypmc + "' and t.yfsb='" + mainform.yfsb + "' " +
                        "order by ypsl";
                    dt0.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));

                    decimal a_var = 0;   //实发数量的临时变量（用于减药房库存）
                    for (int j = 0; j < dt0.Rows.Count; j++)
                    {
                        string ypxh = dt0.Rows[j][1].ToString();
                        string ypph = dt0.Rows[j][2].ToString();
                        if (j == 0)
                        {
                            a_var = Convert.ToDecimal(dataGridView1.Rows[i].Cells[8].Value);
                        }
                        if (a_var <= Convert.ToDecimal(dt0.Rows[j][0]))   //某记录：实发数量<药品数量
                        {
                            a_var = Convert.ToDecimal(dt0.Rows[j][0]) - a_var;

                            comStr = "update yf_kcmx set ypsl=1_var where t.ypxh='" + ypxh + "' and t.ypph='" + ypph + "' and t.yfsb='" + mainform.yfsb + "'";
                            SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                            break;
                        }
                        if (a_var > Convert.ToDecimal(dt0.Rows[j][0]))   //某记录：实发数量>药品数量
                        {
                            a_var = a_var - Convert.ToDecimal(dt0.Rows[j][0]);
                            comStr = "delete yf_kcmx where t.ypxh='" + ypxh + "' and t.ypph='" + ypph + "' and t.yfsb='" + mainform.yfsb + "'";
                            SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                        }
                    }
                }
                tan_tishi = 1;
            }            
        }

        #region datagridView只能输出数字 winform下c#实现datagridview单元格只能输出数字,"02"还不能屏蔽输入
        // 自定义事件   
        private void Cells_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b')
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[6])
                    {
                        e.Handled = true;
                    }
                }
            }
        }
        public DataGridViewTextBoxEditingControl CellEdit = null; // 声明 一个 CellEdit   
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            CellEdit = (DataGridViewTextBoxEditingControl)e.Control;
            CellEdit.SelectAll();
            CellEdit.KeyPress += Cells_KeyPress;
        }
        #endregion

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Tab)
            {
                tabSB = 1;
            }
            else
            {
                tabSB = 0;
            }
        }

        /// <summary>
        /// 实发数量的列总在编辑状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[6])
                {
                    this.dataGridView1.BeginEdit(true);
                }
            }
        }

        /// <summary>
        /// 输入实发数量，回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (tabSB != null)
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    //if 加多一个条件 dataGridView1.Rows[i].Cells[5].Value != "0" 就没有报错，搞不清楚什么原理
                    if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[6] && dataGridView1.Rows[i].Cells[6].Value != null &&
                        dataGridView1.Rows[i].Cells[6].Value.ToString() != "0" && tabSB == 0)
                    {
                        if (float.Parse(dataGridView1.Rows[i].Cells[6].Value.ToString()) <= float.Parse(dataGridView1.Rows[i].Cells[8].Value.ToString()))
                        {
                            if (i<dataGridView1.Rows.Count-1)
                            {
                                dataGridView1.CurrentCell = dataGridView1.Rows[i + 1].Cells[6];
                            }
                        }
                        else
                        {
                            dataGridView1.Rows[i].Cells[6].Value = null;
                            MessageBox.Show("库房没有那么多库存！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        if (dataGridView1.Rows[i].Cells[6].Value != null) //visual studio 问题？ ：外层if的条件没作用，故在里层的if再添加一个相同的条件
                        {
                            if (float.Parse(dataGridView1.Rows[i].Cells[6].Value.ToString()) > float.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString()))
                            {
                                dataGridView1.Rows[i].Cells[6].Value = null;
                                MessageBox.Show("实发数量大于申领数量，请修改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                       
                    }
                }
            }
        }

        /// <summary>
        /// 计算金额和合计，实发数量为空自动补零
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (tabSB != null)         //if(dataGridView1.Focus())这代码，导致焦点不能去到 备注textBox
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {                    
                    //计算金额。出库数量为null，自动填写0。获取合计标识变量。
                    if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[6])
                    {
                        if (dataGridView1.CurrentRow.Cells[6].Value == null)
                        {
                            dataGridView1.CurrentRow.Cells[6].Value = "0";
                        }
                        dataGridView1.Rows[i].Cells[7].Value = ((float.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString())) *
                            (float.Parse((dataGridView1.Rows[i].Cells[6].Value.ToString())))).ToString();
                        totalparameter = 1;
                    }
                }
            }

            //输出出库数量，计算 合计
            if (totalparameter == 1)
            {
                float float1 = 0.00f;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)     //datagridView1总会有一行空白行。
                {
                    if (dataGridView1.Rows[i].Cells[6].Value!=null)
                    {
                        float1 += float.Parse(((float.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString())) *
                            (float.Parse((dataGridView1.Rows[i].Cells[6].Value.ToString())))).ToString());
                    }
                }
                textBox6.Text = float1.ToString();
            }
        }
    }
}
